package com.jhd.jiangxi.downloadmanager.manager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jhd.jiangxi.UtilHelper;
import com.jhd.jiangxi.activity.main.ConfigActivity;
import com.jhd.jiangxi.downloadmanager.DownLoadService;
import com.jhd.jiangxi.downloadmanager.Utils.DeviceUtils;
import com.jhd.jiangxi.service.GetVersionInfo;
import com.jhd.jiangxi.vo.Version;

import net.zigin.commons.util.StringUtil;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/*下载管理类*/
public class UpdateManager {

    private Context mContext;
    private ProgressDialog _progressDialog;
    private Intent _intent = null;
    private DownloadReceiver _downloadReceiver;

    public UpdateManager(Context context) {
        this.mContext = context;
    }

    /*检测软件更新*/
    public void checkUpdate(final boolean isToast) {
        /**
         * 在这里请求后台接口，获取更新的内容和最新的版本号
         */
        Retrofit retrofit = UtilHelper.retrofit(UtilHelper.baseUrls.VERSION);//new Retrofit.Builder().baseUrl("http://118.190.202.144:9000/").addConverterFactory(FastJsonConverterFactory.create()).client(builder.build()).build();
        GetVersionInfo vs = retrofit.create(GetVersionInfo.class);
        Call<String> jsonForResultCall = vs.getVersionInfo();
        jsonForResultCall.enqueue(new UpdateManager.GetVersionInfoCallback());


    }

    private class GetVersionInfoCallback implements Callback<String> {

        @Override
        public void onResponse(Call<String> call, Response<String> response) {

            try {
                String result = response.body();
                if (StringUtil.isNullOrEmpty(result)) return;
                JSONObject json = JSONObject.parseObject(result);
                Version v = JSON.toJavaObject(json, Version.class);
                // 版本的更新信息
                String version_info = v.getInfo();//"更新内容\n" + "    1. 异常处理\n" + "    2. 发布格式统一\n" + "    ";
                int nVersion_code = v.getCode();
                int mVersion_code = DeviceUtils.getVersionCode(mContext);// 当前的版本号

                if (mVersion_code < nVersion_code) {
                    if (v.getForce()) {//强制更新
                        execUpdate();
                    } else {
                        // 显示提示对话
                        showNoticeDialog(version_info);
                    }
                } else {
                    if (mContext instanceof ConfigActivity) {
                        Toast.makeText(mContext, "已经是最新版本", Toast.LENGTH_SHORT).show();
                    }

                }


            } catch (Exception e) {
                Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
            } finally {
//                UtilHelper.scanPower(1, SheetInActivity.this);//恢复扫描功能
            }
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            alertNetError();
//            Toast.makeText(mContext, "网络未连接,稍后再试", Toast.LENGTH_SHORT).show();
        }
    }

    private void execUpdate() {
        //动态注册广播接收器
        _downloadReceiver = new DownloadReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UtilHelper.DOWNLOAD_RECEIVER);
        mContext.registerReceiver(_downloadReceiver, intentFilter);
        initProgressDialog();
        mContext.startService(new Intent(mContext, DownLoadService.class));
    }

    /**
     * 显示更新对话框
     *
     * @param version_info
     */
    private void showNoticeDialog(String version_info) {
        // 构造对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("更新提示");
        builder.setMessage(version_info);
        // 更新
        builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                execUpdate();
            }
        });
        // 稍后更新
        builder.setNegativeButton("以后更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        Dialog noticeDialog = builder.create();
        if (!((Activity) mContext).isFinishing()) noticeDialog.show();
    }

    public class DownloadReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //拿到进度，更新UI
            if (_progressDialog == null) return;
            int progress = intent.getIntExtra("progress", 0);

            if (progress == 100 || progress < 0) {
                _progressDialog.dismiss();
                mContext.unregisterReceiver(_downloadReceiver);
                if (progress < 0) {
                    alertNetError();
                    return;
                }
            } else {
                _progressDialog.setProgress(progress);
            }
        }
    }

    private void alertNetError() {
        try {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("错误");
            builder.setMessage("下载失败,更新没有成功,可能因为网络未连接或不稳定,请在网络正常时再进行更新!");
            builder.setPositiveButton("确定", null);
            Dialog dialog = builder.create();
            if (!((Activity) mContext).isFinishing()) dialog.show();
        } catch (Exception ex) {
            System.out.print(ex.getMessage());
            //避免因异常而调用错误机制造成闪退
        }
    }

    private void initProgressDialog() {
        _progressDialog = new ProgressDialog(mContext);
        _progressDialog.setTitle("下载更新");
        _progressDialog.setMessage("正在下载最新版本,请不要关机或退出,稍等片刻...");
        _progressDialog.setCanceledOnTouchOutside(false);//在外边是否取消
        _progressDialog.setCancelable(false);//不许取消
        _progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        _progressDialog.setMax(100);
        if (!((Activity) mContext).isFinishing()) _progressDialog.show();

    }
}
